package com.woniuxy.countservice.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.model.Result;
import com.woniuxy.countclient.client.OrderFeignClient;
import com.woniuxy.countclient.client.dto.VenueListOrderDto;
import com.woniuxy.countdao.mapper.FlowChartMapper;
import com.woniuxy.countdao.model.FlowChart;
import com.woniuxy.countmodel.dto.FlowChartDto;
import com.woniuxy.countservice.service.FlowChartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@Service
public class FlowChartServiceImpl extends ServiceImpl<FlowChartMapper, FlowChart> implements FlowChartService {
    @Autowired
    private FlowChartMapper flowChartMapper;
    @Resource
    private OrderFeignClient orderFeignClient;
    @Override
    public void add(Integer venueId) {
            Result<List<VenueListOrderDto>> result = orderFeignClient.findByVenueId(venueId);
            List<VenueListOrderDto> orderDtos = result.getData();
            List<VenueListOrderDto> list = new ArrayList<>();
            for (VenueListOrderDto orderDto : orderDtos) {
                if (orderDto.getOrderState() != 0 && orderDto.getOrderState() != 2) {
                    list.add(orderDto);
                }
            }
            //统计每月的销售金额
            Map<String, BigDecimal> yearMonthTotalMap = new HashMap<>();
            for (VenueListOrderDto orderDto : list) {
                String time = orderDto.getOrderCreateTime();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    // 将字符串解析为日期对象
                    Date date = format.parse(time);
                    // 使用Calendar获取年份和月份
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1; // 月份是从0开始计数的，需要加1
                    // 构建年份和月份的标识字符串
                    String yearMonthKey = year + "-" + month;
                    // 获取订单金额
                    BigDecimal orderMoney = orderDto.getOrderMoney();
                    // 将金额累加到对应年份和月份的总数上
                    if (yearMonthTotalMap.containsKey(yearMonthKey)) {
                        BigDecimal totalAmount = yearMonthTotalMap.get(yearMonthKey);
                        totalAmount = totalAmount.add(orderMoney);
                        yearMonthTotalMap.put(yearMonthKey, totalAmount);
                    } else {
                        yearMonthTotalMap.put(yearMonthKey, orderMoney);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            for (Map.Entry<String, BigDecimal> entry : yearMonthTotalMap.entrySet()) {
                String key = entry.getKey();
                String[] parts = key.split("-");
                // 将分割后的子串转换为 int 类型
                int year = Integer.parseInt(parts[0]);
                int month = Integer.parseInt(parts[1]);
                BigDecimal value = entry.getValue();
                QueryWrapper<FlowChart> wrapper = new QueryWrapper<>();
                wrapper.eq("year",year);
                wrapper.eq("month",month);
                wrapper.eq("venue_id",venueId);
                FlowChart chart = flowChartMapper.selectOne(wrapper);
                if(ObjectUtil.isEmpty(chart)){
                    FlowChart flowChart = new FlowChart();
                    flowChart.setYear(year);
                    flowChart.setMonth(month);
                    flowChart.setRevenueAmount(value);
                    flowChart.setVenueId(venueId);
                    flowChartMapper.insert(flowChart);
                }else {
                    chart.setRevenueAmount(value);
                    flowChartMapper.updateById(chart);
                }
            }
            //统计每月的累计成交量
            Map<String, Integer> yearMonthOrderCountMap = new HashMap<>();
            for (VenueListOrderDto orderDto : list) {
                String time = orderDto.getOrderCreateTime();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    // 将字符串解析为日期对象
                    Date date = format.parse(time);
                    // 使用 Calendar 获取年份和月份
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1; // 月份是从0开始计数的，需要加1
                    // 构建年份和月份的标识字符串
                    String yearMonthKey = year + "-" + month;
                    // 统计相同年月的订单数
                    if (yearMonthOrderCountMap.containsKey(yearMonthKey)) {
                        int count = yearMonthOrderCountMap.get(yearMonthKey);
                        yearMonthOrderCountMap.put(yearMonthKey, count + 1);
                    } else {
                        yearMonthOrderCountMap.put(yearMonthKey, 1);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            for (Map.Entry<String, Integer> entry : yearMonthOrderCountMap.entrySet()) {
                String key = entry.getKey();
                String[] parts = key.split("-");
                // 将分割后的子串转换为 int 类型
                int year = Integer.parseInt(parts[0]);
                int month = Integer.parseInt(parts[1]);
                QueryWrapper<FlowChart> wrapper = new QueryWrapper<>();
                wrapper.eq("year",year);
                wrapper.eq("month",month);
                wrapper.eq("venue_id",venueId);
                FlowChart flowChart = flowChartMapper.selectOne(wrapper);
                Integer value = entry.getValue();
                flowChart.setOrderAmouth(value);
                flowChartMapper.updateById(flowChart);
            }
    }

    @Override
    public FlowChart look(Integer chartId) {
        FlowChart flowChart = flowChartMapper.selectById(chartId);
        return flowChart;
    }

    @Override
    public FlowChartDto venueLook(Integer year, Integer month, Integer venueId) {
        QueryWrapper<FlowChart> wrapper = new QueryWrapper<>();
        wrapper.eq("year",year);
        wrapper.eq("month",month);
        wrapper.eq("venue_id",venueId);
        FlowChart flowChart = flowChartMapper.selectOne(wrapper);
        FlowChartDto flowChartDto = BeanUtil.toBean(flowChart, FlowChartDto.class);
        return flowChartDto;
    }
}
